iT邦幫忙

2026 iThome 鐵人賽

DAY 25
0
ChatGPT & Codex

窮鬼冰箱升級計劃系列 第 25 篇

【Day 25】Meshtastic 做 Failover Alert

  • 分享至 

  • xImage
  •  

前言

在冰箱周遭,沒有安裝有線網路的情況下,也想讓冰箱資訊同步出來,因此透過 Meshtastic 讓手機和冰箱互相連線。 本日目標,是希望系統自己判斷網路狀態,如果主要網路失效,就自動改走 Meshtastic 通知。

Primary Path
Wi-Fi / Internet
      │
      ├── OK → 正常使用
      │
      └── FAIL
             ↓
      Secondary Path
       Meshtastic
             ↓
        發送告警

網路狀態

在冰箱的連接 ESP32 / Raspberry Pi / Meshtastic 的情況,有三種網路狀態需要進行偵測。

  1. LAN_OK / 區域網路暢通,可以確保 ESP32 和 Raspberry Pi 之間的通訊。
  2. INTERNET_OK / 網際網路狀態,是偵測冰箱放置地點的路由器,是否能連到外網。
  3. MESH_OK / 網格有通,則可以透過 Mesh 直接和手機交換訊息。

Check LAN

  • 以下程式碼片段,直接用 subprocess 由 python 呼叫子程序執行 ping 指令。
import subprocess


def check_ping(host: str) -> bool:
    result = subprocess.run(
        [
            "ping",
            "-c",
            "1",
            "-W",
            "2",
            host,
        ],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )

    return result.returncode == 0

Check WAN (Internet)

分別檢查可以找到 DNS 和連外網 HTTPS

  1. DNS
    import socket
    
    
    def check_dns() -> bool:
        try:
            socket.gethostbyname(
                "example.com"
            )
            return True
    
        except OSError:
            return False
    
  2. HTTPS
    import requests
    
    
    def check_internet() -> bool:
        try:
            response = requests.get(
                "https://example.com",
                timeout=5,
            )
    
            return (
                200 <= response.status_code < 500
            )
    
        except requests.RequestException:
            return False
    

NetworkHealthService

app/
└── services/
    ├── network_health_service.py
    └── meshtastic_service.py
class NetworkHealthService:

    def check(self):
        lan_ok = self.check_gateway()

        internet_ok = False

        if lan_ok:
            internet_ok = (
                self.check_internet()
            )

        return {
            "lan_ok": lan_ok,
            "internet_ok": internet_ok,
        }

Failover Alert 邏輯

def handle_network_state(
    old_state,
    new_state,
):

    if (
        old_state["internet_ok"]
        and not new_state["internet_ok"]
    ):
        mesh.send(
            "ALERT|WAN|DOWN"
        )

    if (
        not old_state["internet_ok"]
        and new_state["internet_ok"]
    ):
        mesh.send(
            "RECOVERY|WAN|UP"
        )

上一篇
【Day 24】LoRa 無線通訊與 Meshtastic
下一篇
【Day 26】System Health Dashboard
系列文
窮鬼冰箱升級計劃 共 26 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言